<template>
  <common-list>
    <common-search slot="search" @search="handleQuery" @reset="resetQuery">
      <el-form
        :model="queryParams"
        ref="queryForm"
        :inline="true"
        @submit.native.prevent
        v-show="showSearch"
        label-width="85px"
      >
        <el-form-item label="业务系统" prop="applicationSystem">
          <el-select
            v-model="queryParams.applicationSystem"
            class="custom-select"
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option
              class="custom-select"
              v-for="item in businessCodeList"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictLabel"
            >
              <span class="selectList">
                <common-marquee-text :content="item.dictLabel">
                </common-marquee-text>
              </span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="库名/用户名" prop="dbAccount">
          <common-input
            v-model="queryParams.dbAccount"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="数据库名称" prop="dbName">
          <common-input
            v-model="queryParams.dbName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="数据库类型" prop="dbType">
          <el-select
            v-model="queryParams.dbType"
            style="width: 100%"
            filterable
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in dbTypeList"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="表名" prop="tableName">
          <common-input
            v-model="queryParams.tableName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="列名" prop="columnName">
          <common-input
            v-model="queryParams.columnName"
            clearable
            @enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="识别规则" prop="ruleIds">
          <el-select v-model="queryParams.ruleIds" filterable>
            <el-option label="全部" :value="null"></el-option>
            <el-option
              v-for="item in ruleList"
              :key="item.id"
              :label="item.ruleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="识别方式" prop="discernType">
          <el-select
            v-model="queryParams.discernType"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option label="全部" :value="null"></el-option>
            <el-option label="自动识别" :value="0"></el-option>
            <el-option label="人工识别" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </common-search>

    <el-row slot="tools" :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-switch
          v-model="isMatchNums"
          @change="matchNumChange"
          active-color="#13ce66"
          inactive-color="#909399"
          active-text="仅含有敏感字段数据"
          inactive-text="所有数据"
        >
        </el-switch>
      </el-col>
    </el-row>
    <el-row slot="tools" :gutter="10" class="mb8" style="margin-top: 15px">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload2"
          :loading="exportLoading"
          @click="handleExport"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <!-- v-hasPermi="['datascan:scanresult:import']" -->
        <el-button
          type="primary"
          plain
          icon="el-icon-download"
          @click="importShow"
          >导入
        </el-button>
      </el-col>
    </el-row>
    <common-table slot="content" v-loading="loading" :data="list">
      <el-table-column
        label="业务系统"
        width="140"
        align="left"
        prop="applicationSystem"
        fixed
        show-overflow-tooltip
      />
      <el-table-column
        label="数据库名称"
        align="left"
        prop="dbName"
        width="160"
      />
      <el-table-column
        label="数据库类型"
        align="left"
        prop="dbType"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="库名/用户名"
        align="left"
        prop="dbAccount"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        label="表名"
        align="left"
        prop="tableName"
        show-overflow-tooltip
      />
      <el-table-column
        label="列名"
        align="left"
        prop="columnName"
        show-overflow-tooltip
      />
      <el-table-column
        label="列备注"
        align="left"
        prop="columnRemark"
        show-overflow-tooltip
      />
      <el-table-column label="识别方式" align="left" prop="discernType">
        <template slot-scope="scope">
          {{ scope.row.discernType === 0 ? "自动识别" : "人工识别" }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="匹配结果" align="left" prop="approve">
        <template slot-scope="scope">
          <el-tag
            type="success"
            effect="plain"
            v-if="scope.row.approve === '准确'"
            >{{ scope.row.approve }}</el-tag
          >
          <el-tag
            type="danger"
            effect="plain"
            v-else-if="scope.row.approve === '不准确'"
            >{{ scope.row.approve }}</el-tag
          >
          <span v-else>{{ scope.row.approve }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="采样数据"
        align="left"
        prop="remark"
        show-overflow-tooltip
      />
      <el-table-column
        label="IP"
        align="left"
        prop="ip"
        width="160"
        show-overflow-tooltip
      />
      <el-table-column
        label="表行数"
        align="left"
        prop="scanNums"
        show-overflow-tooltip
      />
      <el-table-column
        label="数据分类"
        align="left"
        prop="typeId"
        show-overflow-tooltip
      />
      <el-table-column
        label="数据分级"
        align="left"
        prop="levelId"
        show-overflow-tooltip
      />
      <el-table-column
        label="识别规则"
        align="left"
        prop="label"
        show-overflow-tooltip
      />
      <el-table-column
        label="重要数据"
        align="left"
        prop="importantData"
        show-overflow-tooltip
      />
      <el-table-column
        label="核心数据"
        align="left"
        prop="coreData"
        show-overflow-tooltip
      />
      <el-table-column label="操作" align="center" width="80" fixed="right">
        <template slot-scope="scope">
          <el-dropdown @command="moreTools(scope.row, $event)">
            <span
              class="el-dropdown-link"
              style="cursor: pointer; margin-left: 8px; font-size: 12px"
              :style="{ '--theme-color': systemInfo.theme }"
              v-hasPermi="[
                'datascan:column:edit',
                'datascan:column:query',
                'datascan:column:setDiscerule',
                'datascan:column:setCoreData',
                'datascan:column:setImpData',
              ]"
            >
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown" class="size">
              <el-dropdown-item
                command="rule"
                v-hasPermi="['datascan:column:setDiscerule']"
              >
                设置识别规则
              </el-dropdown-item>
              <el-dropdown-item
                command="coreData"
                v-hasPermi="['datascan:column:setCoreData']"
              >
                设置核心数据
              </el-dropdown-item>
              <el-dropdown-item
                command="importantData"
                v-hasPermi="['datascan:column:setImpData']"
              >
                设置重要数据
              </el-dropdown-item>
              <!-- <el-dropdown-item
                command="edit"
                v-hasPermi="['datascan:column:edit']"
              >
                人工确定
              </el-dropdown-item> -->
              <el-dropdown-item command="showInfo"> 详情 </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
          <!-- <el-button
            type="text"
            @click="showInfo(scope.row)"
            >详情
          </el-button>
          <el-button
            type="text"
            @click="edit(scope.row)"
            v-hasPermi="['datascan:column:edit']"
            >人工确认
          </el-button> -->
          <!--          <el-dropdown-->
          <!--            @command="moreTool(scope.row, $event)"-->
          <!--            v-hasPermi="['datascan:column:edit']"-->
          <!--          >-->
          <!--            <span-->
          <!--              class="el-dropdown-link"-->
          <!--              style="-->
          <!--                cursor: pointer;-->
          <!--                color: #409eff;-->
          <!--                margin-left: 4px;-->
          <!--                font-size: 12px;-->
          <!--              "-->
          <!--            >-->
          <!--              人工确认<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
          <!--            </span>-->
          <!--            <el-dropdown-menu slot="dropdown">-->
          <!--              &lt;!&ndash; <el-dropdown-item command="1">准确</el-dropdown-item>-->
          <!--              <el-dropdown-item command="2">不准确</el-dropdown-item>-->
          <!--              <el-dropdown-item command="0">重置</el-dropdown-item> &ndash;&gt;-->
          <!--              <el-dropdown-item-->
          <!--                command="edit"-->
          <!--                v-hasPermi="['datascan:column:edit']"-->
          <!--                >编辑</el-dropdown-item-->
          <!--              >-->
          <!--            </el-dropdown-menu>-->
          <!--          </el-dropdown>-->
        </template>
      </el-table-column>
    </common-table>

    <pagination
      slot="pagination"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <common-info-dialog
      title="查看详情"
      :visible.sync="infoShow"
      @cancel="hiddenInfo"
    >
      <common-info-table>
        <common-info-table-cell label="数据库类型" width="50%">
          {{ info.dbType }}
        </common-info-table-cell>
        <common-info-table-cell label="字段类型" width="50%">
          {{ info.columnType }}
        </common-info-table-cell>
        <common-info-table-cell label="数据库名称" width="50%">
          {{ info.dbName }}
        </common-info-table-cell>
        <common-info-table-cell label="库名/用户名" width="50%">
          {{ info.dbAccount }}
        </common-info-table-cell>
        <common-info-table-cell label="表名" width="50%">
          {{ info.tableName }}
        </common-info-table-cell>
        <common-info-table-cell label="列名" width="50%">
          {{ info.columnName }}
        </common-info-table-cell>
        <common-info-table-cell label="列备注" width="50%">
          {{ info.columnRemark }}
        </common-info-table-cell>
        <common-info-table-cell label="IP" width="50%">
          {{ info.ip }}
        </common-info-table-cell>
        <common-info-table-cell label="表行数" width="50%">
          {{ info.scanNums }}
        </common-info-table-cell>
        <common-info-table-cell label="数据分类" width="50%">
          {{ info.typeId }}
        </common-info-table-cell>
        <common-info-table-cell label="数据分级" width="50%">
          {{ info.levelId }}
        </common-info-table-cell>
        <common-info-table-cell label="识别规则" width="50%">
          {{ info.label }}
        </common-info-table-cell>
        <common-info-table-cell label="重要数据" width="50%">
          {{ info.importantData }}
        </common-info-table-cell>
        <common-info-table-cell label="核心数据" width="50%">
          {{ info.coreData }}
        </common-info-table-cell>
        <common-info-table-cell label="识别方式" width="50%">
          {{ info.discernType }}
        </common-info-table-cell>
        <common-info-table-cell label="扫描时间" width="100%">
          {{ info.createTime }}
        </common-info-table-cell>
        <common-info-table-cell
          label="采样数据"
          style="height: 100px"
          width="100%"
        >
          {{ info.remark }}
        </common-info-table-cell>
      </common-info-table>
    </common-info-dialog>

    <common-edit-dialog
      title="编辑字段"
      :visible.sync="fieldShow"
      @cancel="fieldShow = false"
      @submit="fieldEditConfirm"
      :buttonLoading="buttonLoading"
    >
      <el-form :model="queryParams" label-width="120px">
        <el-form-item label="编辑前敏感字段：">
          {{ fieldLabel }}
        </el-form-item>

        <el-form-item label="编辑后敏感字段：" prop="wordIds">
          <el-select
            v-model="fieldForm.wordIds"
            placeholder="请选择敏感字段"
            style="width: 100%"
            filterable
            clearable
          >
            <el-option label="非敏感" value="0" />
            <el-option
              v-for="item in wordsList"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </common-edit-dialog>
    <common-upload-dialog
      download-path="system/alarmInfo/downFileByemplateName"
      upload-path="/datascan/b/dbscanresult/importScanResult"
      template-name="alarmTemplate.xls"
      report-path="system/downErrorReportByemplateName"
      ref="uploadDialog"
      :getList="getList"
    />
    <!-- 设置重要数据 -->
    <template v-if="showImportData">
      <set-import-data
        ref="impData"
        :info="itemInfo"
        @close="closeImportDialog"
        @refresh="refresh"
        @save="saveImpData"
      ></set-import-data>
    </template>

    <!-- 设置核心数据 -->
    <template v-if="showCoreData">
      <set-core-data
        ref="coreData"
        :info="itemInfo"
        @close="closeCoreDialog"
        @refresh="refresh"
        @save="saveCoreData"
      ></set-core-data>
    </template>

    <!-- 设置识别规则 -->
    <template v-if="showDiserRule">
      <set-diser-rule
        ref="diserRule"
        :info="itemInfo"
        @close="closeRuleDialog"
        @refresh="refresh"
        @save="saveDiserRule"
      ></set-diser-rule>
    </template>
  </common-list>
</template>

<script>
import {
  queryListByTypeCode,
  queryTableColumnList,
  updateColumnApprove,
  querySensitiveWordsList,
  querySensitiveAllWordsList,
  updateCoreData,
  updateImpData,
  updateDiserRule,
} from "@/api/datascan/scanresults/column";
import { queryList as queryWordsList } from "@/api/datascan/sensitivewords/words";
import InfoTable from "@/components/InfoTable";
import Utils, { formatDate } from "@/utils";
import BaseList from "@/mixins/BaseList";
import { decode } from "@/utils/aesUtils";
import { getSingleArray, getFullDept } from "@/utils/util";
import { mapGetters } from "vuex";
import SetImportData from "./components/setImportData.vue";
import SetCoreData from "./components/setCoreData.vue";
import SetDiserRule from "./components/setDiserRule.vue";
import { queryList } from "@/api/datahandler/discernRule";
import { queryBusinessList } from "@/api/datascan/dbinfo/info";

export default {
  name: "Info",
  mixins: [BaseList],
  components: {
    InfoTable,
    SetImportData,
    SetCoreData,
    SetDiserRule,
  },
  data() {
    return {
      businessCodeList: [],
      exportLoading: false,
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 显示查询条件
      showSearch: true,
      // 总条数
      total: 0,
      // 列的基本信息表格数据
      list: [],
      wordsList: [],
      allWordsList: [],
      dbTypeList: [
        {
          label: "oracle",
          value: "oracle",
        },
        {
          label: "mysql",
          value: "mysql",
        },
        {
          label: "teledb",
          value: "teledb",
        },
        {
          label: "pgsql",
          value: "pgsql",
        },
      ], // 数据库类型
      isMatchNums: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleIds: null,
        matchNums: 0, // 是否包含敏感字符  所有数据时为空字符串 仅包含敏感词时为 0
        dbType: null,
        dbName: null,
        tableName: null,
        wordId: null,
        discernType: null,
        columnName: null,
        telephone: null,
        deptIds: null,
        dbAccount: null,
        applicationSystem: null,
      },
      infoShow: false,
      info: {
        applicationSystem: null,
        dbType: null,
        columnType: null,
        dbName: null,
        dbAccount: null,
        tableName: null,
        columnName: null,
        columnRemark: null,
        label: null,
        discernType: null,
        isApprove: "--",
        remark: null,
        createTime: null,
        ip: null,
        scanNums: null,
        typeId: null,
        levelId: null,
        principal: null,
        telephone: null,
      },
      approveList: [
        {
          label: "--",
          value: null,
        },
        {
          label: "--", // 重置
          value: 0,
        },
        {
          label: "准确",
          value: 1,
        },
        {
          label: "不准确",
          value: 2,
        },
        {
          label: "准确",
          value: 3,
        },
      ],

      fieldShow: false,
      fieldLabel: "",
      fieldForm: {
        wordIds: null,
        scanResultId: null,
        isApprove: 3,
      },
      currentParent: 4,
      singleDeptList: [],

      itemInfo: null,
      // --------重构设置重要数据----------
      showImportData: false,
      showCoreData: false,
      showDiserRule: false,
      ruleList: [],
    };
  },
  computed: {
    ...mapGetters(["systemInfo"]),
  },
  created() {
    this.getList();
    // this.getWordsList();
    this.getDataSourceTypeList();
    this.getQueryWordList();
    this.getRuleList();
    this.queryBusinessCodeList();
  },
  methods: {
    importShow() {
      this.$refs.uploadDialog.show();
    },
    //获取业务系统列表
    queryBusinessCodeList() {
      queryBusinessList().then((res) => {
        if (res && res.code === 200) {
          this.businessCodeList = res.data;
        } else {
          this.businessCodeList = [];
        }
      });
    },
    // 获取识别规则
    getRuleList() {
      queryList({ status: 0 }).then((res) => {
        if (res && res.code === 200) {
          this.ruleList = res.rows;
        } else {
          this.dataList = [];
        }
      });
    },
    saveCoreData(params) {
      updateCoreData(params)
        .then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("操作成功");
            this.refresh();
          } else {
            this.$GlobalErrorConfirm("操作失败", res.msg);
          }
        })
        .finally(() => {
          if (this.showCoreData) this.$refs.coreData.headerLoading = false;
        });
    },
    saveImpData(params) {
      updateImpData(params)
        .then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("操作成功");
            this.refresh();
          } else {
            this.$GlobalErrorConfirm("操作失败", res.msg);
          }
        })
        .finally(() => {
          if (this.showImportData) this.$refs.impData.headerLoading = false;
        });
    },
    saveDiserRule(info) {
      let params = {
        scanResultId: info.id,
        ruleIds: info.ruleIds,
      };
      updateDiserRule(params)
        .then((res) => {
          if (res && res.code === 200) {
            this.$GlobalSuccessMessage("操作成功");
            this.refresh();
          } else {
            this.$GlobalErrorConfirm("操作失败", res.msg);
          }
        })
        .finally(() => {
          if (this.showDiserRule) this.$refs.diserRule.headerLoading = false;
        });
    },
    refresh() {
      this.showImportData = false;
      this.showCoreData = false;
      this.showDiserRule = false;
      this.getList();
    },
    closeImportDialog() {
      this.showImportData = false;
    },
    closeCoreDialog() {
      this.showCoreData = false;
    },
    closeRuleDialog() {
      this.showDiserRule = false;
    },

    getDeptName(val) {
      let dept = this.singleDeptList.find((item) => item.id === val.toString());
      if (dept) return getFullDept(dept.fulllabel);
    },
    handleExport() {
      this.exportLoading = true;
      this.download(
        "datascan/b/dbscanresult/exportTemplate",
        {
          ...this.queryParams,
          pageSize: 10000,
        },
        `扫描结果_列_${new Date().getTime()}.xlsx`,
        1800000
      ).finally(() => {
        this.exportLoading = false;
      });
    },
    moreTools(row, operate) {
      this.itemInfo = row;
      if (operate === "edit") {
        this.edit(row);
      }
      if (operate === "showInfo") {
        this.showInfo(row);
      } else if (operate === "importantData") {
        this.showImportData = true;
      } else if (operate === "coreData") {
        this.showCoreData = true;
      } else if (operate === "rule") {
        this.showDiserRule = true;
      }
    },
    /** 查询列的基本信息列表 */
    getList() {
      this.loading = true;
      queryTableColumnList(this.queryParams)
        .then((res) => {
          if (res && res.code === 200) {
            this.list = res.data.dataList.reduce((r, c) => {
              let approve = this.approveList.find(
                (a) => a.value === c.isApprove
              );
              c.approve = approve ? approve.label : "--";
              if (c.telephone !== "" && c.telephone !== null) {
                c.telephone = Utils.phoneEncryption(decode(c.telephone));
              } else {
                c.telephone = "";
              }
              c.deptName = this.getDeptName(c.deptId || "");
              r.push(c);
              return r;
            }, []);
            this.total = res.data.totalCount;
          } else {
            this.list = [];
            this.total = 0;
            this.handleListTips(res);
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 查询按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = this.$options.data().queryParams;
      // this.$refs.commonDept.clearDept();
    },

    getWordsList() {
      querySensitiveWordsList({}).then((res) => {
        if (res && res.code === 200) {
          this.wordsList = res.data.dataList.reduce((r, c) => {
            r.push({
              label: c.name,
              value: c.wordId,
            });
            return r;
          }, []);
        } else {
          this.wordsList = [];
        }
      });
    },
    getQueryWordList() {
      querySensitiveAllWordsList().then((res) => {
        if (res && res.code === 200) {
          this.allWordsList = res.data.dataList.reduce((r, c) => {
            r.push({
              label: c.name,
              value: c.wordId,
            });
            return r;
          }, []);
        } else {
        }
      });
    },
    showInfo(info) {
      this.info.applicationSystem = info.applicationSystem;
      this.info.dbType = info.dbType;
      this.info.dbName = info.dbName;
      this.info.tableName = info.tableName;
      this.info.ip = info.ip;
      this.info.dbAccount = info.dbAccount;
      this.info.scanNums = info.scanNums;
      this.info.typeId = info.typeId;
      this.info.levelId = info.levelId;
      this.info.principal = info.principal;
      this.info.telephone = info.telephone;
      this.info.columnName = info.columnName;
      this.info.columnType = info.columnType;
      this.info.columnRemark = info.columnRemark;
      this.info.label = info.label;
      this.info.discernType = info.discernType === 0 ? "自动识别" : "人工识别";
      this.info.remark = info.remark;
      let approve = this.approveList.find((a) => a === info.isApprove);
      this.info.isApprove = approve ? approve.label : "--";
      this.info.createTime = formatDate(info.createTime);
      this.info.deptId = this.getDeptName(info.deptId || "");
      this.info.importantData = info.importantData;
      this.info.coreData = info.coreData;
      this.infoShow = true;
    },
    matchNumChange() {
      this.queryParams.matchNums = this.isMatchNums ? 0 : "";
      this.handleQuery();
    },
    hiddenInfo() {
      this.infoShow = false;
    },
    edit(row) {
      this.fieldShow = true;
      this.fieldForm.scanResultId = row.scanResultId;
      this.fieldLabel = row.label;
      this.fieldForm.wordIds = "0";
    },
    moreTool(column, command) {
      if (command === "edit") {
        this.fieldShow = true;
        this.fieldForm.scanResultId = column.scanResultId;
        this.fieldLabel = column.label;
        this.fieldForm.wordIds = "0";
      } else {
        updateColumnApprove({
          scanResultIds: column.scanResultId,
          isApprove: command,
        }).then((res) => {
          if (res && res.code === 200) {
            this.getList();
            this.$GlobalSuccessMessage("操作成功");
          } else {
            this.$GlobalErrorConfirm("操作失败", res.msg);
          }
        });
      }
    },
    fieldEditConfirm() {
      this.buttonLoading = true;
      updateColumnApprove(this.fieldForm)
        .then((res) => {
          if (res && res.code === 200) {
            this.getList();
            this.$GlobalSuccessMessage("操作成功");
          } else {
            this.$GlobalErrorConfirm("操作失败", res.msg);
          }
        })
        .finally(() => {
          this.fieldShow = false;
          this.buttonLoading = false;
        });
    },
    getDataSourceTypeList() {
      queryListByTypeCode().then((res) => {
        if (res && res.code === 200) {
          this.dbTypeList = res.data.dataList.reduce((r, c) => {
            r.push({
              label: c.name,
              value: c.value,
            });
            return r;
          }, []);
        } else {
          this.dbTypeList = [];
        }
      });
    },
  },
};
</script>
<style scoped lang="scss">
.el-dropdown-menu__item {
  font-size: 12px;
}
::v-deep .info-table-row-value {
  overflow-y: auto;
}

.el-dropdown-link {
  color: var(--theme-color);
}
</style>
